package cn.maihe.elg.operation.web.order;

import cn.maihe.elg.operation.exception.ErrorCode;
import cn.maihe.elg.operation.exception.SystemRuntimeException;
import cn.maihe.elg.operation.model.bo.ApplyTemplatePdfParams;
import cn.maihe.elg.operation.model.dto.BaseResponse;
import cn.maihe.elg.operation.model.enums.AcceptOrderStatus;
import cn.maihe.elg.operation.model.enums.AttachmentFileType;
import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.model.enums.GuaranteeCategory;
import cn.maihe.elg.operation.model.enums.GuaranteeType;
import cn.maihe.elg.operation.model.enums.RevokeFlagEnum;
import cn.maihe.elg.operation.model.enums.UserType;
import cn.maihe.elg.operation.model.vo.order.AcceptOrderDetailVO;
import cn.maihe.elg.operation.model.vo.order.AcceptOrderMatchPayInfoVO;
import cn.maihe.elg.operation.model.vo.order.AcceptOrderPayOperateVO;
import cn.maihe.elg.operation.model.vo.order.AcceptOrderStatusAuditVO;
import cn.maihe.elg.operation.model.vo.order.ListAcceptOrderVO;
import cn.maihe.elg.operation.model.vo.order.OrderStatusSumVO;
import cn.maihe.elg.operation.model.vo.order.OrderTemplateIdReqVO;
import cn.maihe.elg.operation.model.vo.order.OrderTemplateIdRespVO;
import cn.maihe.elg.operation.model.vo.order.SaveInviteCodeVO;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeAttachmentInfoDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeInstitutionDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeProgressInfoDO;
import cn.maihe.elg.operation.repository.entity.SpdBankNotice;
import cn.maihe.elg.operation.security.model.UserContext;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.business.ExchangeCenterService;
import cn.maihe.elg.operation.service.business.InstitutionService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.service.order.GuaranteeAttachmentInfoService;
import cn.maihe.elg.operation.service.order.GuaranteeProgressInfoService;
import cn.maihe.elg.operation.supports.electronicseal.kt.mixca.MixCaSignService;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.CreateGuaranteeUtil;
import cn.maihe.elg.operation.utils.DateUtil;
import cn.maihe.elg.operation.utils.DownloadExcelTool;
import cn.maihe.elg.operation.utils.StringUtil;
import cn.maihe.elg.operation.utils.UserContextUtil;
import cn.maihe.framework.starter.base.sql.PageBo;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 受理出函订单管理
 * @Author WJH
 * @Date 2021/05/06
 */
@Api(value = "受理出函订单管理", tags = "受理出函订单管理")
@RestController
@RequestMapping("/api")
@Slf4j
public class AcceptOrderInfoController {

    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;
    @Resource
    private GuaranteeProgressInfoService guaranteeProgressInfoService;
    @Resource
    private DownloadExcelTool downloadExcelTool;
    @Resource
    private ElgResourceService elgResourceService;
    @Resource
    private BidCustomerService bidCustomerService;
    @Resource
    private GuaranteeAttachmentInfoService guaranteeAttachmentInfoService;
    @Resource
    private MixCaSignService mixCaSignService;
    @Resource
    private InstitutionService institutionService;
    @Resource
    private ExchangeCenterService exchangeCenterService;

    @ApiOperation(value = "首页订单统计信息", notes = "首页订单统计信息")
    @RequestMapping(value = "/orderTotal", method = RequestMethod.POST)
    public OrderStatusSumVO getOrderTotal() {
        OrderStatusSumVO sumVO = acceptOrderInfoService.orderTotal();
        if (sumVO == null) {
            sumVO = OrderStatusSumVO.builder()
                    .waitTrailCount(0L)
                    .waitTuneUpCount(0L)
                    .waitOfferCount(0L)
                    .waitPayCount(0L)
                    .waitPayConfirmCount(0L)
                    .waitGuaranteeCount(0L)
                    .guaranteedCount(0L)
                    .revokedCount(0L)
                    .revokingCount(0L)
                    .warnCount(0L)
                    .build();
        }
        sumVO.setBidCount(bidCustomerService.totalAudit());
        return sumVO;
    }

    @ApiOperation(value = "分页查询受理订单信息", notes = "根据受理订单 录入参数 分页查询")
    @RequestMapping(value = "/acceptOrders", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "centerOrderId", value = "订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "bidCustomerName", value = "申请企业名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sectionName", value = "标段名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "guaranteeType", value = "保函类型", dataType = "int", paramType = "query", allowableValues = "0,1,2,3"),
            @ApiImplicitParam(name = "guaranteeCategory", value = "保函品种", dataType = "int", paramType = "query", allowableValues = "0,1,2,3,4"),
            @ApiImplicitParam(name = "acceptOrderStatus", value = "订单状态", dataType = "int", paramType = "query", allowableValues = "0,1,2,3,4,5,6,7,8,9"),
            @ApiImplicitParam(name = "centerName", value = "交易中心名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "guarantorName", value = "出函机构名称", dataType = "String", paramType = "query"),

    })
    public PageBo<AcceptOrderDetailVO> pageList(int pageNo, int pageSize, ListAcceptOrderVO vo) {
        return acceptOrderInfoService.selectPageBySql(pageNo, pageSize, vo);
    }

    @RequestMapping(value = "/acceptOrder/defaultTemplateId", method = RequestMethod.GET)
    public OrderTemplateIdRespVO defaultTemplateId(OrderTemplateIdReqVO vo) {
        return acceptOrderInfoService.defaultTemplateId(vo);
    }

    @ApiOperation(value = "获取受理订单信息", notes = "根据受理订单信息id获取受理订单信息")
    @ApiImplicitParam(name = "id", value = "受理订单信息id", dataType = "String", paramType = "path", required = true)
    @RequestMapping(value = "/acceptOrder/{id}", method = RequestMethod.GET)
    public AcceptOrderDetailVO getAcceptOrderDetailById(@PathVariable String id) {
        AcceptOrderInfoDO cur = acceptOrderInfoService.getByAcceptOrderNo(id);
        Long ids = null;
        if (cur != null) {
            ids = cur.getId();
        } else {
            ids = Long.parseLong(id);
        }

        AcceptOrderDetailVO curVO = acceptOrderInfoService.getAcceptOrderDetailById(ids);
        if (curVO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单信息id");
        }
        //判断操作人员，判断状态 下发签章信息
        if (curVO.getStatus() == AcceptOrderStatus.WAIT_FIRST_TRAIL.getStatus() ||
                curVO.getStatus() == AcceptOrderStatus.WAIT_PAY.getStatus() ||
                curVO.getStatus() == AcceptOrderStatus.WAIT_PAY_CONFIRM.getStatus()) {
            UserContext userContext = UserContextUtil.getUserContext();
            if (userContext.getUserType().intValue() == UserType.BIDDER.getType()) {
                if (curVO.getProtocolUnSignedFile() == null) {
                    //生成未签章文件
                    GuaranteeAttachmentInfoDO guaranteeAttachmentInfo = makeAndSaveApplyFile(curVO);
                    if (guaranteeAttachmentInfo != null) {
                        curVO.setProtocolUnSignedFile(guaranteeAttachmentInfo);
                    }
                }
                if (curVO.getProtocolFile() == null) {
                    curVO.setApplyFileReadFlag("0");
                    Path path = elgResourceService.getAbsolutePath(curVO.getProtocolUnSignedFile().getFilePath());
                    curVO.setSignString(mixCaSignService.buildMixCaBase64(path, curVO.getAcceptOrderNo()));
                }else {
                    curVO.setApplyFileReadFlag("1");
                }
            }
        }

        return curVO;
    }

    private GuaranteeAttachmentInfoDO makeAndSaveApplyFile(AcceptOrderDetailVO curVo) {
        ApplyTemplatePdfParams params = new ApplyTemplatePdfParams();
        params.setBidderName(curVo.getBidderName());
        params.setProjectName(curVo.getProjectName());
        Triple<String, String, String> triple = DateUtil.parseLocalDate();
        params.setYear(triple.getLeft());
        params.setMonth(triple.getMiddle());
        params.setDay(triple.getRight());
        ;
        String acceptOrderNo = curVo.getAcceptOrderNo();
        Path pdfPath = elgResourceService.buildApplyFileByTemplate(acceptOrderNo, params);
        AcceptOrderInfoDO orderInfo = AcceptOrderInfoDO.of(curVo);
        GuaranteeAttachmentInfoDO guaranteeAttachmentInfoDO = guaranteeAttachmentInfoService.saveOrUpdateAttachmentInfo(orderInfo, pdfPath, AttachmentFileType.TYPE_12, "申请书未签章");
        return guaranteeAttachmentInfoDO;
    }


    @ApiOperation(value = "订单状态审核", notes = "审核待初审、待尽调、待报价、支付确认操作")
    @ApiImplicitParam(name = "id", value = "受理订单信息id", dataType = "long", paramType = "path", required = true)
    @RequestMapping(value = "/acceptOrder/auditStatus", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Boolean auditStatus(@RequestBody AcceptOrderStatusAuditVO vo) {
        if (vo.getBatchType() != null && StringUtils.isNoneBlank(vo.getIds())) {

            Arrays.stream(vo.getIds().split(",")).forEach(id -> {
                long curId = Long.valueOf(id);
                AcceptOrderStatusAuditVO curVO = new AcceptOrderStatusAuditVO();
                BeanUtils.copyProperties(vo, curVO);
                curVO.setId(curId);
                auditStatusSingle(curVO);
            });
            return true;
        } else {
            return auditStatusSingle(vo);
        }

    }

    @ApiOperation(value = "人工调整待支付订单状态为待支付确认状态", notes = "人工调整待支付订单状态为待支付确认状态")
    @RequestMapping(value = "/acceptOrder/manualConfirm", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Boolean manualConfirm(@RequestParam("id") long id) {
        AcceptOrderInfoDO curDO = acceptOrderInfoService.selectById(id);
        if (curDO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单信息id");
        }
        if (curDO.getStatus() == null || curDO.getStatus().intValue() != AcceptOrderStatus.WAIT_PAY.getStatus()) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "原受理订单不是待支付状态,不能人工操作");
        }
        AcceptOrderInfoDO updateDO = AcceptOrderInfoDO.builder().id(id).status(AcceptOrderStatus.WAIT_PAY_CONFIRM.getStatus())
                .remark("人工调整待支付订单状态为待支付确认状态").build();
        acceptOrderInfoService.updateById(updateDO);
        return true;
    }


    @ApiOperation(value = "订单取消", notes = "订单取消")
    @RequestMapping(value = "/acceptOrder/cancelOrder", method = RequestMethod.PUT)
    public Boolean cancelOrder(@RequestBody AcceptOrderPayOperateVO vo) {
        AcceptOrderInfoDO curDO = acceptOrderInfoService.selectById(vo.getId());
        if (curDO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单信息id");
        }
        if (curDO.getStatus() == null || curDO.getStatus().intValue() != vo.getStatus().intValue()) {
            AcceptOrderStatus status = AcceptOrderStatus.resolve(curDO.getStatus().intValue());
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单状态为" + status.getDesc() + ",请刷新订单列表重试");
        }
        AcceptOrderStatus status = AcceptOrderStatus.resolve(vo.getStatus().intValue());

        if (vo.getCancelType() != null && vo.getCancelType().equals("quitApply")) {
            log.warn("人工退保操作员：{},请求参数：{}", UserContextUtil.getCurUserName(), JSON.toJSONString(vo));
            String acceptOrderNo = vo.getAcceptOrderNo();
            if (StringUtils.isEmpty(acceptOrderNo)) {
                throw new RuntimeException("受理订单号不能为空");
            }
            if (status == AcceptOrderStatus.WAIT_OUT_GUARANTEE || status == AcceptOrderStatus.HAS_OUT_GUARANTEE) {
                return acceptOrderInfoService.manualQuitApply(acceptOrderNo);
            } else {
                throw new SystemRuntimeException(ErrorCode.ERROR, "受理订单非待出函或已出函状态，不能退保");
            }
        } else {
            //todo:alan 待支付确认状态取消订单有可能与自动出函并发，导致订单状态不正确
            if (status.equals(AcceptOrderStatus.WAIT_PAY) || status.equals(AcceptOrderStatus.WAIT_PAY_CONFIRM)) {
                log.warn("人工取消订单操作员：{},请求参数：{}", UserContextUtil.getCurUserName(), JSON.toJSONString(vo));
                return acceptOrderInfoService.cancelOrder(vo);
            } else {
                throw new SystemRuntimeException(ErrorCode.ERROR, "受理订单非待支付或待支付确认状态，不能取消");
            }
        }
    }

    @ApiOperation(value = "订单退保申请", notes = "订单退保申请")
    @RequestMapping(value = "/acceptOrder/revokeOrder", method = RequestMethod.PUT)
    public Boolean revokeOrder(@RequestBody AcceptOrderPayOperateVO vo) {
        AcceptOrderInfoDO curDO = acceptOrderInfoService.getByAcceptOrderNo(vo.getAcceptOrderNo());
        if (curDO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单信息acceptOrderNo");
        }
        if (curDO.getStatus() == null || curDO.getStatus().intValue() != vo.getStatus().intValue()) {
            AcceptOrderStatus status = AcceptOrderStatus.resolve(curDO.getStatus().intValue());
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单状态为" + status.getDesc() + ",请刷新订单列表重试");
        }
        if (vo.getCancelType() != null && vo.getCancelType().equals("revokeApply")) {
            return acceptOrderInfoService.revokeApply(curDO);
        }
        return false;
    }

    @ApiOperation(value = "订单支付凭证上传", notes = "订单支付凭证上传")
    @RequestMapping(value = "/acceptOrder/payInfo", method = RequestMethod.PUT)
    public Boolean payInfo(@RequestBody AcceptOrderPayOperateVO vo) {
        AcceptOrderInfoDO curDO = acceptOrderInfoService.selectById(vo.getId());
        if (curDO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单信息id");
        }
        if (curDO.getStatus() == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单状态异常为空，请联系客服人员处理");
        }

        CenterNoEnum centerNoEnum = exchangeCenterService.getCenterNoEnumById(curDO.getCenterId());
        if(CreateGuaranteeUtil.isMeiShan(centerNoEnum)){
            if(!"1".equals(vo.getApplyFileReadFlag())){
                throw new SystemRuntimeException(ErrorCode.ERROR, "请阅读并同意《委托申请书、反担保承诺书》的用章");
            }

            Path signedPdfPath = elgResourceService.buildSaveAbsolutePath("ofd", curDO.getAcceptOrderNo(), "已签章担保保函申请书", "pdf");
            GuaranteeAttachmentInfoDO protocolUnSignedFile = guaranteeAttachmentInfoService.getTypeAttachmentByAcceptOrderNo(curDO.getAcceptOrderNo(), AttachmentFileType.TYPE_12);
            Path path = elgResourceService.getAbsolutePath(protocolUnSignedFile.getFilePath());
            try {
                byte[] fileBytes = Files.readAllBytes(path);
                Files.copy(new ByteArrayInputStream(fileBytes), signedPdfPath, StandardCopyOption.REPLACE_EXISTING);
                GuaranteeAttachmentInfoDO protocolFile = guaranteeAttachmentInfoService.getTypeAttachmentByAcceptOrderNo(curDO.getAcceptOrderNo(), AttachmentFileType.TYPE_11);
                if (protocolFile == null) {
                    mixCaSignService.saveSignedApplyFile(curDO.getAcceptOrderNo(), signedPdfPath, null);
                }
            } catch (IOException e) {
                throw new SystemRuntimeException(ErrorCode.ERROR, e, "《委托授权书、担保承诺书》的合成失败");
            }
        }

        AcceptOrderStatus status = AcceptOrderStatus.resolve(vo.getStatus().intValue());
        if (status == AcceptOrderStatus.WAIT_FIRST_TRAIL) {
            return acceptOrderInfoService.submitSignedInfo(vo);
        } else if (status.equals(AcceptOrderStatus.WAIT_PAY)) {
            return acceptOrderInfoService.submitPayInfo(vo);
        } else if (status.equals(AcceptOrderStatus.WAIT_PAY_CONFIRM) || status.equals(AcceptOrderStatus.HAS_OUT_GUARANTEE)) {
           return acceptOrderInfoService.submitInviteCodeInfo(vo);
        }else if (curDO.getStatus().intValue() != vo.getStatus().intValue()) {
            status = AcceptOrderStatus.resolve(curDO.getStatus().intValue());
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单状态为" + status.getDesc() + ",请刷新订单列表重试");
        }
        else {
            throw new SystemRuntimeException(ErrorCode.ERROR, "受理订单非待支付状态，暂不能发起签署");
        }

    }

    private Boolean auditStatusSingle(AcceptOrderStatusAuditVO vo) {
        AcceptOrderInfoDO curDO = acceptOrderInfoService.selectById(vo.getId());
        if (curDO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "受理订单信息id");
        }
        if (curDO.getStatus() == null || curDO.getStatus().intValue() != vo.getStatus().intValue()) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "原受理订单状态与库表状态不一致");
        }
        AcceptOrderStatus status = AcceptOrderStatus.resolve(vo.getStatus().intValue());

        switch (status) {
            case WAIT_FIRST_TRAIL: {
                //待初审--审核操作
                return acceptOrderInfoService.auditWaitFirstTrail(vo);
            }
            case WAIT_SUBMIT_FIRST_TRAIL: {
                // 保函模板审核--通过则待支付确认，不通过则返回待签署，客户调整修改后在提交
                return acceptOrderInfoService.auditGuaranteeTemplateId(vo);
            }
            case WAIT_TUNE_UP: {
                //待尽调--审核操作
                return acceptOrderInfoService.auditWaitTuneUp(vo);
            }
            case WAIT_OFFER: {
                //待报价--审核操作
                return acceptOrderInfoService.auditWaitOffer(vo);
            }
            case WAIT_PAY:
            case WAIT_PAY_CONFIRM: {
                //待支付--待支付确认--审核操作
                return acceptOrderInfoService.manualAuditWaitPayConfirm(vo, curDO.getAcceptOrderNo());
            }
            case REVOKE_PROCESSING: {
                // 撤销退保审核操作
                RevokeFlagEnum revokeFlagEnum = RevokeFlagEnum.resolve(curDO.getRevokeFlag());
                if (revokeFlagEnum != RevokeFlagEnum.PROCESSING) {
                    throw new SystemRuntimeException(ErrorCode.ERROR, "受理订单非退保审核状态，不能进行退保审核操作");
                } else {
                    acceptOrderInfoService.auditRevokeOrder(curDO, vo.getAuditStatus(), vo.getAuditRemark());
                }
                return true;
            }
            default: {
                throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "暂不支持该状态[" + vo.getStatus() + "]审核操作");
            }
        }
    }

    @ApiOperation(value = "获取订单历史记录", notes = "根据受理订单号获取订单历史记录")
    @ApiImplicitParam(name = "acceptOrderNo", value = "受理订单号", dataType = "string", paramType = "query", required = true)
    @RequestMapping(value = "/acceptOrder/guaranteeProgressInfo", method = RequestMethod.GET)
    public List<GuaranteeProgressInfoDO> guaranteeProgressInfo(@RequestParam String acceptOrderNo) {
        return guaranteeProgressInfoService.selectGuaranteeProgressInfos(acceptOrderNo);
    }

    @RequestMapping(value = "/acceptOrder/download", method = RequestMethod.POST)
    public void downloadAcceptOrder(HttpServletResponse response, @RequestBody ListAcceptOrderVO vo) {
        vo.setIsDownload(true);
        PageBo<AcceptOrderDetailVO> pageBo = acceptOrderInfoService.selectPageBySql(1, DownloadExcelTool.maxRowNum, vo);
        List<AcceptOrderDetailVO> list = pageBo.getList().stream().map(l -> {
            l.setGuaranteeTypeName(GuaranteeType.getDescByType(l.getGuaranteeType()));
            l.setGuaranteeCategoryName(GuaranteeCategory.getDescByType(l.getGuaranteeCategory()));
            l.setStatusName(AcceptOrderStatus.getDescByStatus(l.getStatus()));
            l.setGuaranteeFeeYuan(StringUtil.toYuan(l.getGuaranteeFee()));
            return l;
        }).collect(Collectors.toList());
        downloadExcelTool.downloadByTemplateName("acceptOrderReport.xlsx", "我的受理订单", response, list, null);
    }

    @ApiOperation(value = "获取订单匹配支付流水记录", notes = "根据受理订单号获取订单匹配支付流水记录")
    @ApiImplicitParam(name = "acceptOrderNo", value = "受理订单号", dataType = "string", paramType = "query", required = true)
    @RequestMapping(value = "/acceptOrder/selectMatchPayInfos", method = RequestMethod.GET)
    public List<AcceptOrderMatchPayInfoVO> selectMatchPayInfos(@RequestParam String acceptOrderNo) {
        List<SpdBankNotice> spdBankNoticeList = acceptOrderInfoService.selectMatchPayInfos(acceptOrderNo);
        List<AcceptOrderMatchPayInfoVO> acceptOrderMatchPayInfoVoList = new ArrayList<>(spdBankNoticeList.size());
        spdBankNoticeList.stream().forEach(spdBankNotice -> {
            AcceptOrderMatchPayInfoVO acceptOrderMatchPayInfoVo = new AcceptOrderMatchPayInfoVO();
            BeanUtils.copyProperties(spdBankNotice, acceptOrderMatchPayInfoVo);
            acceptOrderMatchPayInfoVoList.add(acceptOrderMatchPayInfoVo);
        });
        return acceptOrderMatchPayInfoVoList;
    }

    @ApiOperation(value = "保存业务编码", notes = "保存业务编码")
    @RequestMapping(value = "/acceptOrder/saveInviteCode", method = RequestMethod.PUT)
    public BaseResponse<Object> saveInviteCode(@RequestBody SaveInviteCodeVO vo) {
        UserContext uc = UserContextUtil.getUserContext();
        if(Objects.isNull(uc)){
            return BaseResponse.error("请登录后，再操作");
        }

        if(UserType.BIDDER.getType() == uc.getUserType()){
            AcceptOrderInfoDO acceptOrderInfoDO = acceptOrderInfoService.selectById(vo.getAcceptOrderId());
            if(Objects.isNull(acceptOrderInfoDO)){
                return BaseResponse.error("订单不存在");
            }
            if(!acceptOrderInfoDO.getBidCustomerId().equals(uc.getBidderId())){
                return BaseResponse.error("非法操作，不允许修改");
            }
        }else {
            if (UserType.GENERAL.getType() != uc.getUserType()) {
                return BaseResponse.error("权限不足，不允许修改");
            }
        }
        acceptOrderInfoService.saveInviteCode(vo.getAcceptOrderId(),vo.getInviteCode());
        return BaseResponse.success();
    }

    @ApiOperation(value = "获取出函机构", notes = "根据受理订单对出函机构id获取出函机构")
    @ApiImplicitParam(name = "id", value = "出函机构id", dataType = "long", paramType = "path", required = true)
    @RequestMapping(value = "/acceptOrder/institution/{id}", method = RequestMethod.GET)
    public GuaranteeInstitutionDO getInstitution(@PathVariable Long id) {
        GuaranteeInstitutionDO curDO = institutionService.selectById(id);
        if (curDO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "出函机构id");
        }
        return curDO;
    }
}
